package com.kerbores.nutz.freemarker;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

import org.nutz.ioc.loader.json.JsonLoader;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Streams;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.resource.NutResource;
import org.nutz.resource.Scans;

/**
 * 预定义的Freemarker Ioc配置
 * 
 * @author rekoe
 *
 */
public class FreemarkerIocLoader extends JsonLoader {
	Log log = Logs.get();

	public FreemarkerIocLoader(String path) {
		_load(path);
	}

	public FreemarkerIocLoader() {
		_load("freemarker.js");
	}

	@SuppressWarnings("unchecked")
	public void _load(String path) {
		log.debug("loading...   path:---> " + path);
		List<NutResource> resources = Scans.me().scan(path);
		for (NutResource resource : resources) {
			InputStream in = null;
			try {
				in = resource.getInputStream();
				String s = Lang.readAll(new InputStreamReader(in));
				Map<String, Map<String, Object>> map = (Map<String, Map<String, Object>>) Json.fromJson(s);
				if (null != map && map.size() > 0)
					getMap().putAll(map);
			} catch (Exception e) {
				if (e instanceof RuntimeException)
					throw (RuntimeException) e;
				throw new RuntimeException("load fail , path=" + path, e);
			} finally {
				Streams.safeClose(in);
			}
		}
	}
}
